package com.hidataplus.hadoop.tezui;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.naming.Context;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.util.Hashtable;
import java.util.Locale;

public class UserLogin {

    public static Logger logger = LoggerFactory.getLogger(UserLogin.class);
    public static boolean checkPassword(User user) {
//        if (user.getPassword().equals(user.getUsername())) {
//            return true;
//        }
//
//        return false;

        String loginType = Config.getUserLoginTye().toLowerCase();
        if(loginType.equals("simple")){
            return  user.getPassword().equals(user.getUsername());
        }
        else if(loginType.equals("ldap")){
            return checkLdapUser(user);
        }else{
            logger.error("usre login type： " + loginType + " is not supported! ");
            return false;
        }
    }


    public static boolean checkLdapUser(User user) {

        DirContext ctx = null;

        Hashtable env = new Hashtable();

//        String userNameRegx = "cn=${username},dc=example,dc=org";
        String userNameRegx = Config.getUserLoginLdapUserNameRegex();
        String ldapUser = userNameRegx.replace("${username}",user.getUsername());
        logger.info("ldap user:" + ldapUser);
//        String ldapUrl = "ldap://49.232.213.253:1389/";
        String ldapUrl = Config.getUserLoginLdapUrl();
        logger.info("ldapUrl:" + ldapUrl);

        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapUrl);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, ldapUser);
        env.put(Context.SECURITY_CREDENTIALS, user.getPassword());
        try {
            ctx = new InitialDirContext(env);
            logger.info("ldap auth success!");
            return true;
        } catch (Exception e) {
            System.out.println("ldap auth fail：" + e.toString());
        }
        return false;
    }
}
